package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.google.j2objc.annotations.AutoreleasePool;
import com.tanhua.model.mongo.UserLocation;
import javafx.scene.effect.Light;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class UserLocationApiImpl implements UserLocationApi {
@Autowired
private MongoTemplate mongoTemplate;
    @Override
    public List<Long> findNear(Long userId, String distance) {
        //以当前用户的经纬度为圆心，距离长度为半径画圆，判断在圆范围里的用户则返回给前端
        //查询圆点
        Criteria criteria = Criteria.where("userId").is(userId);
        Query query = Query.query(criteria);
        UserLocation one = mongoTemplate.findOne(query, UserLocation.class);
        GeoJsonPoint point = one.getLocation();
        //创建半径，距离，需要double类型
        Double value = Double.valueOf(distance);
        // KILOMETERS是千米，我们传入的是米，用的是Distance的构造方法为距离赋值
        Distance distance1 = new Distance(value/1000, Metrics.KILOMETERS);  //数据，单位
        Circle circle = new Circle(point, distance1);//圆点和半径
        //查找坐标在该圆覆盖的区域用户
        Criteria criteria1 = Criteria.where("location").withinSphere(circle);
        Query query1 = Query.query(criteria1);
        List<UserLocation> userLocations = mongoTemplate.find(query1, UserLocation.class);
        List<Long> ids = CollUtil.getFieldValues(userLocations, "userId", Long.class);
        return ids;
    }
}
